﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" :rules="formRules" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>访客基本信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="姓名" tooltip="访客姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Phone_FormItem" prop="Entity.Phone">
								<template #label>
									<WtmLabelTooltip label="手机号" tooltip="访客手机号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Phone" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_IdCardNo_FormItem"
								prop="Entity.IdCardNo"
								:rules="[{ required: true, message: '身份证号为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="身份证号" tooltip="访客身份证号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.IdCardNo" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Company_FormItem" prop="Entity.Company">
								<template #label>
									<WtmLabelTooltip label="所属单位/公司" tooltip="访客所属单位或公司" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Company" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_CarNo_FormItem" prop="Entity.CarNo">
								<template #label>
									<WtmLabelTooltip label="车牌号" tooltip="访客车辆车牌号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.CarNo" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>身份信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_IdCardFrontPhotoId_FormItem" prop="Entity.IdCardFrontPhotoId">
								<template #label>
									<WtmLabelTooltip label="身份证人像面" tooltip="身份证人像面文件" />
								</template>
								<wtm-upload-image v-model="stateData.vmModel.Entity.IdCardFrontPhotoId" clearable class="width100"></wtm-upload-image>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_IdCardBackPhotoId_FormItem" prop="Entity.IdCardBackPhotoId">
								<template #label>
									<WtmLabelTooltip label="身份证国徽面" tooltip="身份证国徽面文件" />
								</template>
								<wtm-upload-image v-model="stateData.vmModel.Entity.IdCardBackPhotoId" clearable class="width100"></wtm-upload-image>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>预约信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_VisitorReasonId_FormItem" prop="Entity.VisitorReasonId">
								<template #label>
									<WtmLabelTooltip label="访客事由" tooltip="访客事由" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.VisitorReasonId" clearable class="width100">
									<el-option v-for="item in stateData.AllSysVisitorReasons" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ReservationTime_FormItem" prop="Entity.ReservationTime">
								<template #label>
									<WtmLabelTooltip label="预约时间" tooltip="预约时间" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.ReservationTime" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Receptionist_FormItem" prop="Entity.Receptionist">
								<template #label>
									<WtmLabelTooltip label="接待人" tooltip="接待人姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Receptionist" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ReceptionistPhone_FormItem" prop="Entity.ReceptionistPhone">
								<template #label>
									<WtmLabelTooltip label="接待人电话" tooltip="接待人电话" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.ReceptionistPhone" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_GroupId_FormItem" prop="Entity.GroupId">
								<template #label>
									<WtmLabelTooltip label="被访部门" tooltip="被访问的部门" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.GroupId" clearable class="width100">
									<el-option v-for="item in stateData.AllSysGroups" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>流程信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Approver_FormItem" prop="Entity.Approver">
								<template #label>
									<WtmLabelTooltip label="审批人" tooltip="流程审批人" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Approver" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ApprovalTime_FormItem" prop="Entity.ApprovalTime">
								<template #label>
									<WtmLabelTooltip label="审批时间" tooltip="流程审批时间" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.ApprovalTime" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_RejectReason_FormItem" prop="Entity.RejectReason">
								<template #label>
									<WtmLabelTooltip label="拒绝原因" tooltip="拒绝原因" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.RejectReason" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>访客出入信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_EntryTime_FormItem" prop="Entity.EntryTime">
								<template #label>
									<WtmLabelTooltip label="入厂时间" tooltip="入厂时间" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.EntryTime" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_LeaveTime_FormItem" prop="Entity.LeaveTime">
								<template #label>
									<WtmLabelTooltip label="出厂时间" tooltip="出厂时间" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.LeaveTime" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, type ComponentInternalInstance } from 'vue';
import { SysVisitorRecordRequestBillApi as api } from '/@/views/visitor/sysvisitorrecordrequestbill/api';
import other from '/@/utils/other';
import { ISysVisitorRecordRequestBillVm } from '/@/views/visitor/sysvisitorrecordrequestbill/api/interface';
import { IViewModel } from '/@/types/common';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const API_ENDPOINTS = {
	VISITOR_REASONS: '/api/SysVisitorRecordRequestBill/GetSysVisitorReasons',
	FRAMEWORK_USERS: '/api/SysVisitorRecordRequestBill/GetFrameworkUsers',
	GROUPS: '/api/SysVisitorRecordRequestBill/GetSysGroups',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);

// 表单验证规则
const formRules = {
	'Entity.VisitorReasonId': [{ required: true, message: '请选择访客事由', trigger: 'change' }],
	'Entity.Name': [{ required: true, message: '请输入访客姓名', trigger: 'blur' }],
	'Entity.Phone': [{ required: true, message: '请输入访客手机号', trigger: 'blur' }],
	'Entity.ReservationTime': [{ required: true, message: '请选择预约时间', trigger: 'change' }],
	'Entity.Receptionist': [{ required: true, message: '请输入接待人', trigger: 'blur' }],
	'Entity.ReceptionistPhone': [{ required: true, message: '请输入接待人电话', trigger: 'blur' }],
	'Entity.GroupId': [{ required: true, message: '请选择被访部门', trigger: 'change' }],
};

const stateData = reactive<IViewModel<ISysVisitorRecordRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			VisitorReasonId: null,
			Name: null,
			Phone: null,
			IdCardNo: null,
			IdCardFrontPhotoId: null,
			IdCardBackPhotoId: null,
			Company: null,
			CarNo: null,
			UserId: null,
			ReservationTime: null,
			Receptionist: null,
			ReceptionistPhone: null,
			RejectReason: null,
			EntryTime: null,
			LeaveTime: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		},
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysVisitorReasons: [] as any[],
	AllFrameworkUsers: [] as any[],
	AllSysGroups: [] as any[],
});

// 计算属性
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

const canSubmit = computed(() => hasEntityId.value && hasSavedOnce.value);

// 统一的成功处理函数
const handleSuccess = (response: any, isSubmit = false) => {
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
		if (response?.Entity?.ID) {
			stateData.vmModel.Entity = response.Entity;
		} else if (response?.ID) {
			(stateData.vmModel.Entity as any).ID = response.ID;
		}
		hasSavedOnce.value = true;
	}

	loading.value = false;
	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleSuccess(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		false
	);
};

// 提交
const onSubmit = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
		},
		true
	);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		(stateData.vmModel.Entity as any).ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [visitorReasons, frameworkUsers, groups, billCode] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.VISITOR_REASONS, [], false),
		other.getSelectList(API_ENDPOINTS.FRAMEWORK_USERS, [], false),
		other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
		api().getBillCode(),
	]);

	if (visitorReasons.status === 'fulfilled') stateData.AllSysVisitorReasons = visitorReasons.value;
	if (frameworkUsers.status === 'fulfilled') stateData.AllFrameworkUsers = frameworkUsers.value;
	if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
	if (billCode.status === 'fulfilled') stateData.vmModel.Entity.BillCode = billCode.value.Data as string;
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
